<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { $t } from '#/locales';
import { useMagicKeys, whenever } from '@vueuse/core';
import { message } from 'ant-design-vue';

import type { InfoGroupApi } from '#/api/spa/group';
import type { InfoStoreApi } from '#/api/spa/store';
import type { SiteApi } from '#/api/spa/site';
import { getInfoGroupPage } from '#/api/spa/group';
import { getInfoStoreWithGroupPage } from '#/api/spa/store';
import { getSiteList } from '#/api/spa/site';
import { loginByHeader } from '#/api/shop/shop-auth';
import { useGroupSwitchStore } from '#/stores/group-switch';
import { useSiteStore } from '#/stores/site';
import { useStoreSwitchStore } from '#/stores/store-switch';
import { useThreeLevelManager } from '#/stores/three-level-manager';

// Stores
const groupSwitchStore = useGroupSwitchStore();
const storeSwitchStore = useStoreSwitchStore();
const siteStore = useSiteStore();
const threeLevelManager = useThreeLevelManager();
const { closeOtherTabs, refreshTab } = useTabs();

// I18n
// const { t } = useI18n();

// Modal
const [Modal, modalApi] = useVbenModal({
  draggable: true,
  overlayBlur: 5,
  footer: false,
  onCancel: () => {
    modalApi.close();
    currentStep.value = 'group'; // Reset step on close
    threeLevelManager.closeThreeLevelSwitch();
  },
});

// State
const currentStep = ref<'group' | 'site' | 'store'>('group');
const groups = ref<InfoGroupApi.InfoGroup[]>([]);
const stores = ref<InfoStoreApi.InfoStore[]>([]);
const sites = ref<SiteApi.Site[]>([]);

const selectedGroup = ref<InfoGroupApi.InfoGroup | null>(
  groupSwitchStore.getCurrentGroup(),
);
const selectedStore = ref<InfoStoreApi.InfoStore | null>(
  storeSwitchStore.getCurrentStore(),
);
const selectedSite = ref<SiteApi.Site | null>(
  siteStore.getCurrentSiteInfo() as SiteApi.Site | null,
);

// 防抖状态
const isProcessing = ref(false);

// 监听管理器的控制
watch(
  () => threeLevelManager.showThreeLevelSwitch.value,
  (show) => {
    if (show) {
      // 设置初始步骤
      currentStep.value = threeLevelManager.initialStep.value;
      // 打开弹窗
      modalApi.open();
      // 根据步骤加载数据
      if (currentStep.value === 'group') {
        fetchGroups();
      } else if (currentStep.value === 'store' && selectedGroup.value) {
        fetchStores(selectedGroup.value.id);
      } else if (currentStep.value === 'site' && selectedStore.value) {
        fetchSites(selectedStore.value.id);
      }
    } else {
      // 关闭弹窗
      modalApi.close();
    }
  }
);

// Computed properties for display
const modalTitle = computed(() => {
  let title = `${$t('spa.checkout.threeLevelSwitch')} (Alt+KeyG)`;
  if (selectedGroup.value) {
    title += ` - ${$t('spa.checkout.group')}: ${selectedGroup.value.groupName}`;
  }
  if (selectedStore.value) {
    title += ` - ${$t('spa.checkout.store')}: ${selectedStore.value.storeName}`;
  }
  if (selectedSite.value) {
    title += ` - ${$t('spa.checkout.site')}: ${selectedSite.value.site_name}`;
  }
  return title;
});

// Fetch data functions
async function fetchGroups() {
  try {
    const res = await getInfoGroupPage({ pageNo: 1, pageSize: 100 });
    groups.value = res.list || [];
  } catch (error) {
    console.error('获取集团列表失败:', error);
    message.error($t('spa.checkout.switchFailed'));
  }
}

async function fetchStores(groupId: number) {
  try {
    const res = await getInfoStoreWithGroupPage({
      pageNo: 1,
      pageSize: 100,
      groupId,
    });
    stores.value = res.list || [];
  } catch (error) {
    console.error('获取门店列表失败:', error);
    message.error($t('spa.checkout.switchFailed'));
  }
}

async function fetchSites(groupId: number) {
  try {
    const res = await getSiteList({ group_id:groupId  });
    sites.value = res.data || [];
  } catch (error) {
    console.error('获取站点列表失败:', error);
    message.error($t('spa.checkout.switchFailed'));
  }
}

// Handlers
async function handleSelectGroup(group: InfoGroupApi.InfoGroup) {
  selectedGroup.value = group;
  selectedStore.value = null; // Reset store and site on group change
  selectedSite.value = null;
  await fetchStores(group.id);
  await fetchSites(group.id);
  currentStep.value = 'store';
}

function handleSelectStore(store: InfoStoreApi.InfoStore) {
  selectedStore.value = store;
  // If store has siteInfo, try to pre-select the first site
  if (store.siteInfo) {
    try {
      const parsedSites = JSON.parse(store.siteInfo);
      if (Array.isArray(parsedSites) && parsedSites.length > 0) {
        const firstSiteInfo = parsedSites[0];
        const matchingSite = sites.value.find(
          (s) => s.site_id === firstSiteInfo.siteId,
        );
        selectedSite.value = matchingSite || null;
      }
    } catch (error) {
      console.error('解析门店站点信息失败:', error);
    }
  } else {
    selectedSite.value = null;
  }
  currentStep.value = 'site';
}

function handleSelectSite(site: SiteApi.Site) {
  selectedSite.value = site;
}

async function handleCompleteSwitch() {
  // 防抖处理
  if (isProcessing.value) {
    return;
  }

  if (!selectedGroup.value || !selectedStore.value || !selectedSite.value) {
    message.warn($t('spa.checkout.pleaseSelectComplete'));
    return;
  }

  // 设置处理状态
  isProcessing.value = true;

  try {
    // 1. 更新Store状态
    groupSwitchStore.switchGroup(selectedGroup.value);
    storeSwitchStore.switchStore(selectedStore.value);
    siteStore.setCurrentSiteInfo({
      siteId: selectedSite.value.site_id,
      siteName: selectedSite.value.site_name,
      siteDomain: selectedSite.value.site_domain,
      groupId: selectedSite.value.group_id,
      groupName: selectedSite.value.group_name,
      status: selectedSite.value.status,
      statusName: selectedSite.value.status_name,
    });

    // 2. 调用Shop认证接口
    try {
      const authResult = await loginByHeader(
        selectedSite.value.site_id,
        selectedGroup.value.id,
      );
      if (authResult) {
        // 直接使用后端返回的数据结构
        siteStore.setShopAuthInfo(authResult);
      }
    } catch (authError) {
      message.warn($t('spa.checkout.authFailedButSwitchComplete'));
    }

    // 3. 处理待处理的请求
    threeLevelManager.processPendingRequests();

    // 4. 刷新页面
    await closeOtherTabs();
    await refreshTab();
    modalApi.close();
    threeLevelManager.closeThreeLevelSwitch();
    message.success(
      `${$t('spa.checkout.switchSuccess')} ${$t('spa.checkout.group')}: ${selectedGroup.value.groupName}, ${$t('spa.checkout.store')}: ${selectedStore.value.storeName}, ${$t('spa.checkout.site')}: ${selectedSite.value.site_name}`,
    );
  } catch (error) {
    message.error($t('spa.checkout.switchFailed'));
  } finally {
    // 重置处理状态
    isProcessing.value = false;
  }
}

function handleBack() {
  if (currentStep.value === 'site') {
    currentStep.value = 'store';
  } else if (currentStep.value === 'store') {
    currentStep.value = 'group';
  }
}

function handleCancel() {
  // 清除待处理的请求
  threeLevelManager.clearPendingRequests();
  // 关闭弹窗
  modalApi.close();
  threeLevelManager.closeThreeLevelSwitch();
}

function handleRese$t() {
  selectedGroup.value = null;
  selectedStore.value = null;
  selectedSite.value = null;
  currentStep.value = 'group';
  fetchGroups(); // Refetch groups
}

// Watch for modal open to fetch initial data
watch(modalApi.visible, (visible) => {
  if (visible) {
    handleRese$t(); // Reset and fetch groups when modal opens
  }
});

// Shortcut to open modal
const keys = useMagicKeys();
whenever(keys['Alt+KeyG']!, () => {
  modalApi.open();
});

// Helper function to parse site info
function parseSiteInfo(siteInfo: string) {
  try {
    const parsed = JSON.parse(siteInfo);
    return Array.isArray(parsed) ? parsed : [];
  } catch (error) {
    console.error('解析站点信息失败:', error);
    return [];
  }
}

// Initial fetch
fetchGroups();
</script>

<template>
  <Modal class="w-4/5" :title="modalTitle">
    <div class="p-4">
      <div class="mb-4 flex items-center justify-between">
        <a-steps :current="currentStep === 'group' ? 0 : currentStep === 'store' ? 1 : 2" class="flex-1">
          <a-step :title="$t('spa.checkout.selectGroup')" />
          <a-step :title="$t('spa.checkout.selectStore')" />
          <a-step :title="$t('spa.checkout.selectSite')" />
        </a-steps>
        <div class="flex items-center gap-2 ml-4">
          <a-button v-if="currentStep !== 'group'" @click="handleBack">{{ $t('spa.checkout.back') }}</a-button>
          <a-button @click="handleReset">{{ $t('spa.checkout.reset') }}</a-button>
        </div>
      </div>

      <!-- Group Selection -->
      <div v-if="currentStep === 'group'">
        <h3 class="text-lg font-semibold mb-4">{{ $t('spa.checkout.selectGroup') }}</h3>
        <a-list :data-source="groups" :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card :title="item.groupName" hoverable @click="handleSelectGroup(item)" :class="{ 'selected-card': selectedGroup?.id === item.id }">
                <p>{{ $t('spa.checkout.groupCode') }}: {{ item.groupCode }}</p>
                <p>{{ $t('spa.checkout.contactPerson') }}: {{ item.contactPerson }}</p>
                <p>{{ $t('spa.checkout.contactPhone') }}: {{ item.contactPhone }}</p>
                <p>{{ $t('spa.checkout.address') }}: {{ item.address }}</p>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <!-- Store Selection -->
      <div v-if="currentStep === 'store'">
        <h3 class="text-lg font-semibold mb-4">{{ $t('spa.checkout.selectStore') }} ({{ $t('spa.checkout.group') }}: {{ selectedGroup?.groupName }})</h3>
        <a-list :data-source="stores" :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }">
          <template #renderItem="{ item }">
            <a-list-item>
              <a-card :title="item.storeName" hoverable @click="handleSelectStore(item)" :class="{ 'selected-card': selectedStore?.id === item.id }">
                <p>{{ $t('spa.checkout.storeCode') }}: {{ item.storeCode }}</p>
                <p>{{ $t('spa.checkout.contactPerson') }}: {{ item.contactPerson }}</p>
                <p>{{ $t('spa.checkout.contactPhone') }}: {{ item.contactPhone }}</p>
                <p>{{ $t('spa.checkout.address') }}: {{ item.address }}</p>
                <div v-if="item.siteInfo" class="site-tags mt-2">
                  <a-tag v-for="site in parseSiteInfo(item.siteInfo)" :key="site.siteId" :title="`${$t('spa.checkout.siteName')}: ${site.siteName}\n${$t('spa.checkout.siteDomain')}: ${site.siteDomain || $t('spa.checkout.none')}\n${$t('spa.checkout.group')}: ${site.groupName}\n${$t('spa.checkout.status')}: ${site.statusName}`">
                    {{ site.siteName }}
                  </a-tag>
                </div>
                <span v-else class="text-gray-400 text-sm mt-2">{{ $t('spa.checkout.noBoundSites') }}</span>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </div>

      <!-- Site Selection -->
      <div v-if="currentStep === 'site'">
        <h3 class="text-lg font-semibold mb-4">{{ $t('spa.checkout.selectSite') }} ({{ $t('spa.checkout.store') }}: {{ selectedStore?.storeName }})</h3>
        <a-list :data-source="sites" :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }">
          <template #renderItem="{ item }">
            <a-list-item>
                     <a-card :title="item.site_name" hoverable @click="handleSelectSite(item)" :class="{ 'selected-card': selectedSite?.site_id === item.site_id }">
                <p>{{ $t('spa.checkout.siteDomain') }}: {{ item.site_domain || $t('spa.checkout.none') }}</p>
                <p>{{ $t('spa.checkout.group') }}: {{ item.group_name }}</p>
                <p>{{ $t('spa.checkout.status') }}: {{ item.status_name }}</p>
                <p>{{ $t('spa.checkout.address') }}: {{ item.full_address }}</p>
              </a-card>
            </a-list-item>
          </template>
        </a-list>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="border-t pt-4 mt-4 flex justify-end gap-3">
      <a-button size="large" @click="handleCancel">
        {{ $t('spa.checkout.cancel') }}
      </a-button>
      <a-popconfirm
        :title="`${$t('spa.checkout.confirmSwitch')}\n\n${$t('spa.checkout.confirmSwitchContent')}\n\n${$t('spa.checkout.group')}: ${selectedGroup?.groupName}\n${$t('spa.checkout.store')}: ${selectedStore?.storeName}\n${$t('spa.checkout.site')}: ${selectedSite?.site_name}`"
        :ok-text="$t('spa.checkout.confirm')"
        :cancel-text="$t('spa.checkout.cancel')"
        @confirm="handleCompleteSwitch"
      >
        <a-button
          type="primary"
          size="large"
          :disabled="!selectedGroup || !selectedStore || !selectedSite || isProcessing"
          :loading="isProcessing"
        >
          {{ isProcessing ? $t('spa.checkout.processing') : $t('spa.checkout.confirm') }}
        </a-button>
      </a-popconfirm>
    </div>
  </Modal>
</template>

<style scoped>
.selected-card {
  border: 2px solid #1890ff;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.5);
}
.site-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-top: 8px;
}
</style>
